<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\File;
use App\Models\Bus\Bus;
use App\Models\Insure\Insure;
use App\Models\Bus\BusQualificationFile;
use App\Models\Insure\InsureFile;

class updateBusFileByDir extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'update:busFileByDir';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '更新车辆保险行驶证';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $adminPath = public_path('storage/bus/车辆扫描资料');
        $adminFiles = File::allFiles($adminPath);
        $adminFiles = $this->getFilesNamePathByDir($adminFiles);
        $this->updateBusFile($adminFiles);
        $this->info("- Done.");
    }

    public function getFilesNamePathByDir($files)
    {
        $data = [];
        $type = [
            'invoice_url' => '发票',
            'qualified_certificate_url' => '合格证',
            'sign_certificate_url' => '登记证书',
        ];
        $basePath = config('app.url').'/storage/bus/';
        $storage = '车辆扫描资料/';
        foreach ($files as $k => $file) {
            $name = $file->getRelativePath();
            $baseName = str_replace('.jpg', '', $file->getBasename());
            $key = array_search($baseName, $type, true);
            if($key) {
                $data[$name][$key] = $basePath.$storage.$name.'/'.$file->getFileName();
            }
        }

        return collect($data);
    }

    public function updateBusFile($files): void
    {
        foreach ($files as $licensePlateNum => $urls) {
            $photo = Bus::query()->where('license_plate_num', $licensePlateNum)->update($urls);
            if ($photo) {
                $this->info("- Yes: $licensePlateNum");
            } else {
                $this->info("- No: $licensePlateNum");
            }
        }
    }
}
